#!/bin/bash

# check if there exists a image named "custom-dind" 
# if not, build it
if [ "$(docker images -q custom-dind:latest 2> /dev/null)" == "" ]; then
    echo "Image custom-dind:latest not found, building..."
    docker build -t custom-dind:latest .
else
    echo "Image custom-dind:latest already exists."
fi

# start 1-4 network containers
for i in {1..4}; do
    echo "Starting container custom-dind-$i"
    ./start_container.sh "$i"
done 

# execute prepare-all.sh in each container
# save the output to a log file in the container
for i in {1..4}; do
    echo "Executing prepare-all.sh in custom-dind-$i"
    docker exec -it "custom-dind-$i" /bin/bash -c "./prepare-all.sh"
    if [ $? -ne 0 ]; then
        echo "Failed to execute prepare-all.sh in custom-dind-$i"
    else
        echo "prepare-all.sh executed successfully in custom-dind-$i"
    fi
done

# ./cp_into_container.sh
# run the backend in each container
for i in {1..4}; do
    echo "Running backend in custom-dind-$i"
    docker exec -d "custom-dind-$i" /bin/bash -c "cd /backend/cmd && go run main.go > /backend/logs/backend.log 2>&1"   
    if [ $? -ne 0 ]; then
        echo "Failed to run backend in custom-dind-$i"
    else
        echo "Backend running successfully in custom-dind-$i"
    fi
done
